<?php

function __autoload($className){
	require_once $className.'.php';
}

/**
 * This file contains functions that are used throughout the Search app.  They usually did not fit 
 * in any object or other category file.  These functions may be used by several other files.
 * @author Kenn North <kenn.norht@ni.com>
 * @package Core
 * @version 1.0
 */

function array_value_sort($named_recs, $order_by, $rev=false, $flags=0)
{// Create 1-dimensional named array with just
 // sortfield (in stead of record) values
    $named_hash = array();
     foreach($named_recs as $key=>$fields)
             $named_hash["$key"] = $fields[$order_by];
 
 // Order 1-dimensional array,
 // maintaining key-value relations  
    if($reverse) arsort($named_hash,$flags=0) ;
    else asort($named_hash, $flags=0);
 
 // Create copy of named records array
 // in order of sortarray 
    $sorted_records = array();
    foreach($named_hash as $key=>$val)
           $sorted_records["$key"]= $named_recs[$key];
 
	return $sorted_records;
}

function trim_value(&$value) 
{
	$value = trim($value);
}

function greatescape($text)
{
	if (!ini_get("magic_quotes_gpc")) {
		return (addslashes($text));
	} else {
		return $text;
	}
}

function ungreatescape($text)
{
	if (ini_get("magic_quotes_gpc")) {
		return (stripslashes($text));
	} else {
		return $text;
	}
}

/**
 * This function performs several simple operations to a string to prepare
 * it for a safe mySQL query.
 * @param	string	$value		String to make safe
 * @return	string	The safe string
 */

function make_safe( $value )
{
   // Stripslashes
   if ( get_magic_quotes_gpc() ) {
       $value = stripslashes( $value );
   }
   // Quote if not integer
   if ( !is_numeric( $value ) ) {
       $value = "'" . mysql_real_escape_string( $value ) . "'";
   }
   return $value;
}

function redirect($location)
{
	if (strpos($_SERVER["SERVER_SOFTWARE"], "IIS")!==FALSE) {
		// Do a meta refresh. Resolves refresh problem when setting cookies
		// with Microsoft IIS servers 5.0 and lower.
		echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0;URL=".$location."\">";
	} else {
		header ("Location: ".$location);
	}
}
function checkcookies()
{
	$ok=FALSE;

	if (!empty($_COOKIE["userid"])&&!empty($_COOKIE["userpass"])) {
		$result=doquery("select password, username from user where id = ".$_COOKIE["userid"]);
		if (mysql_num_rows($result)==1) {
			$row=mysql_fetch_assoc($result);
			if ($row["password"]==$_COOKIE["userpass"]) {
				$ok=TRUE;
			}
		}
	}
	if (!$ok) {
		setcookie("userid");
		setcookie("userpass");
		setcookie("username");
		header("Location: login.php");
		die();
	}
}
/**
 * Prepares URLs or other text for HTML.  Essensially it replaces & with &amp; if not already done.
 * It also replaces all other special HTML characters
 * @param	string	$value		String to prepare
 * @return	string	The prepared string string
 */

function prepare_html( $value )
{
    return htmlspecialchars ( $value, ENT_QUOTES, 'ISO-8859-1' );
}


/**
 * Calculates a percent match on a string
 *
 * This function calculates a basic percent match on a search string
 * in a string.  It assigns percentage as follows:
 * If either the search string or string are NULL : 0%
 * If search string equals string : 100%
 * If search string is the same except case : 95%
 * If neither of these is satisfied than the percentage is calculated
 * as 85% times the number of word in the search string that 
 * were contained in the string divided by the number of words
 * in the search string.
 * @param	string	$search		The string to search for
 * @param	string	$string		The string to search in
 * @return	double	a percentage between 0 (0%) and 1 (100%)
 */

function string_match( $search, $string ) {
	if ( $search == NULL || $string == NULL ) return 0;	//check if either strings are NULL
	if ( strcmp( $search, $string ) == 0 ) {
		return 1;
	}
	if ( strcasecmp( $search, $string ) == 0 ) {
		return .95;
	}
	if ( stripos( $string, $search ) !== false ) {
		return .90;
	}
	$string = ' '.$string;
	$search =  explode( ' ',$search );
	$words = count( $search );
	$match = 0.0;
	for ( $i = 0; $i < $words; $i++ ) {
		if ( stripos( $string, $search[$i] ) !== false ) $match += 1;
	}
	if ( $words ) {
		return .85 * $match / $words;
	} 
	return 0;
}

/**
 * Function returns the number of days in a month given the month number and year
 * @param	int	$month		The month number The month number (ie January = 1, February = 2, ... December = 12)
 * @param	int	$year		The 4 digit year
 * @return	int	Number of days in month
 */

function month_last_day( $month, $year ) {
	
	if ( $month == 1 || $month == 3 || $month == 5 || $month == 7 || $month == 8 || $month == 10 || $month == 12) return 31;
	if ( $month == 2) {
		if( ( $year % 4 ) == 0 ) {
			if ( ( $year % 100 ) == 0 && ( $year % 400 ) != 0 ) return 28;
			return 29;
		}
		return 28;
	}
	return 30;
}

/**
 * Returns elements that have keys that contain a certain string in an array
 * @param	array	$array		Array given
 * @param	string	$key		String to search for in keys
 * @return	array	Array containing elements that met the correct criteria
 */

function array_by_keys( $array, $key ) {
	$new_array = array();
	foreach( $array as $keys => $values ) {
		if ( stripos( $keys, $key ) !== false ) {
			$new_array[$keys] = $values;
		}
	}
	return $new_array;
}

/**
 * Logs a user out, clearing all session variables and destroying session
 */
function logout() {
	//unset session variables
	$_SESSION = array();
	//delete session cookie if exsists
	if ( isset( $_COOKIE[session_name()] ) ) {
		setcookie( session_name(), '', time() - 42000, '/' );
	}
	//destroy session
	session_destroy();
}


// Form Processing Functions

/**
 * Gets the form_process data from the session and clears the session of the form.  Returns form's object.
 * @return	Object		the form's process object.
 */

function clear_action () {
	global $page;
	if ( isset( $_SESSION['action_process'] ) && is_a ( $_SESSION['action_process'], 'Action_Process') ) {
		$action_process = $_SESSION['action_process'];
		$_SESSION['action_process'] = NULL;
		// Clear wait window that is created by some actions.
		$page->add_javascript(	'win = window.open(\'\',\'wait\');
								win.close();');

		return $action_process;
	}
	return new Action_Process();
}

function details($thing) {
	ob_start();
	echo "<pre>";
	print_r($thing);
	echo "</pre>";
	$contents = ob_get_contents();
	ob_end_clean();
	return $contents;
}

// Converts $title to Title Case, and returns the result.
function strtotitle($title){ 
	// Our array of 'small words' which shouldn't be capitalised if 
	// they aren't the first word. Add your own words to taste. 
	$smallwordsarray = array( 'of','a','the','and','an','or','nor','but','is','if','then','else','when', 'at','from','by','on','off','for','in','out','over','to','into','with' ); 
	// Split the string into separate words 
	$words = explode(' ', $title); foreach ($words as $key => $word) { 
		// If this word is the first, or it's not one of our small words, capitalise it 
		// with ucwords(). 
		if ($key == 0 or !in_array($word, $smallwordsarray)) $words[$key] = ucwords($word); } 
		// Join the words back into a string 
		$newtitle = implode(' ', $words); 
	return $newtitle; 
}

function saneempty($value)
{
	if (strlen($value)==0)
		return TRUE;
	else
		return FALSE;
}
?>